package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.article.dtos.LoginResultDTO;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.user.entity.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    private static final int EXPIRE_MINUTE = 120;
    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * app端用户登录
     * @param dto
     * @return
     */
    @Override
    public LoginResultDTO login(AppLoginDto dto) {
        //判断是否匿名
        if (StringUtils.isEmpty(dto.getPhone())||StringUtils.isEmpty(dto.getPassword())){
            String token = JwtUtils.generateTokenExpireInMinutes(0,EXPIRE_MINUTE);
            return new LoginResultDTO(token, new AdUserDto());
        }else {
            // 不是匿名，走登录逻辑
            // 根据手机号查用户信息
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, dto.getPhone());
            ApUser userDB = this.getOne(queryWrapper);
            if (userDB == null) {
                throw new LeadException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            // 密码的匹配
            String passwordDB = userDB.getPassword();
            String passwordInput = dto.getPassword();
            boolean matches = encoder.matches(passwordInput, passwordDB);
            if (!matches) {
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 判断用户的状态
            Boolean status = userDB.getStatus();
            if (status != null && !status) {
                throw new LeadException(AppHttpCodeEnum.USER_STATUS_ERROR);
            }
            // 生成token，user返回
            LoginResultDTO result = new LoginResultDTO();
            result.setUser(BeanHelper.copyProperties(userDB, AdUserDto.class));
            result.setToken(JwtUtils.generateTokenExpireInMinutes(userDB.getId(), EXPIRE_MINUTE));
            return result;
        }
    }
}
